package com.zenithmind.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.common.result.ResultCode;
import com.zenithmind.library.mapper.BorrowRecordMapper;
import com.zenithmind.library.mapper.FineRecordMapper;
import com.zenithmind.library.pojo.domain.BorrowRecord;
import com.zenithmind.library.pojo.domain.FineRecord;
import com.zenithmind.library.pojo.dto.FineRecordCreateDTO;
import com.zenithmind.library.pojo.dto.FineRecordUpdateDTO;
import com.zenithmind.library.pojo.query.FineRecordQuery;
import com.zenithmind.library.pojo.vo.FineRecordVO;
import com.zenithmind.library.service.FineRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 罚金记录服务实现类
 * 遵循单一职责原则：只负责罚金记录相关的业务逻辑
 * 遵循依赖倒置原则：依赖抽象接口而非具体实现
 * 
 * @author ZenithMind
 * @since 2024-06-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FineRecordServiceImpl extends ServiceImpl<FineRecordMapper, FineRecord> implements FineRecordService {

    private final FineRecordMapper fineRecordMapper;
    private final BorrowRecordMapper borrowRecordMapper;

    @Value("${library.fine.daily-rate:1.0}")
    private BigDecimal dailyFineRate;

    @Value("${library.fine.max-amount:100.0}")
    private BigDecimal maxFineAmount;

    @Override
    @Cacheable(value = "fineRecords", key = "'page:' + #query.hashCode()")
    public PageResult<FineRecordVO> getFineRecordPage(FineRecordQuery query) {
        log.info("分页查询罚金记录，查询条件：{}", query);

        // 构建查询条件
        LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
        
        if (query.getUserId() != null && !query.getUserId().trim().isEmpty()) {
            wrapper.eq(FineRecord::getUserId, query.getUserId());
        }
        
        if (query.getBorrowRecordId() != null && !query.getBorrowRecordId().trim().isEmpty()) {
            wrapper.eq(FineRecord::getBorrowRecordId, query.getBorrowRecordId());
        }
        
        if (query.getFineType() != null) {
            wrapper.eq(FineRecord::getFineType, query.getFineType());
        }
        
        if (query.getPaymentStatus() != null) {
            wrapper.eq(FineRecord::getPaymentStatus, query.getPaymentStatus());
        }
        
        if (query.getMinFineAmount() != null) {
            wrapper.ge(FineRecord::getFineAmount, query.getMinFineAmount());
        }

        if (query.getMaxFineAmount() != null) {
            wrapper.le(FineRecord::getFineAmount, query.getMaxFineAmount());
        }
        
        if (query.getCreateStartDate() != null) {
            wrapper.ge(FineRecord::getCreateTime, query.getCreateStartDate().atStartOfDay());
        }
        
        if (query.getCreateEndDate() != null) {
            wrapper.le(FineRecord::getCreateTime, query.getCreateEndDate().atTime(23, 59, 59));
        }
        
        wrapper.orderByDesc(FineRecord::getCreateTime);

        // 分页查询
        Page<FineRecord> page = new Page<>(query.getCurrent(), query.getSize());
        IPage<FineRecord> result = page(page, wrapper);

        // 转换为VO
        List<FineRecordVO> vos = result.getRecords().stream()
                                      .map(this::convertToVO)
                                      .collect(Collectors.toList());

        return PageResult.of(vos, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    @Cacheable(value = "fineRecords", key = "#id")
    public Result<FineRecordVO> getFineRecordById(String id) {
        log.info("根据ID查询罚金记录详情，ID：{}", id);

        if (id == null || id.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID不能为空", null);
        }

        FineRecord fineRecord = getById(id);
        if (fineRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "罚金记录不存在", null);
        }

        FineRecordVO vo = convertToVO(fineRecord);
        return Result.success(vo);
    }

    @Override
    public Result<List<FineRecordVO>> getFineRecordsByUserId(String userId, Integer status) {
        log.info("根据用户ID查询罚金记录，用户ID：{}，状态：{}", userId, status);

        if (userId == null || userId.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "用户ID不能为空", null);
        }

        LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FineRecord::getUserId, userId);
        
        if (status != null) {
            wrapper.eq(FineRecord::getPaymentStatus, status);
        }
        
        wrapper.orderByDesc(FineRecord::getCreateTime);

        List<FineRecord> fineRecords = list(wrapper);
        List<FineRecordVO> vos = fineRecords.stream()
                                           .map(this::convertToVO)
                                           .collect(Collectors.toList());

        return Result.success(vos);
    }

    @Override
    public Result<List<FineRecordVO>> getFineRecordsByBorrowRecordId(String borrowRecordId) {
        log.info("根据借阅记录ID查询罚金记录，借阅记录ID：{}", borrowRecordId);

        if (borrowRecordId == null || borrowRecordId.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "借阅记录ID不能为空", null);
        }

        LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FineRecord::getBorrowRecordId, borrowRecordId)
               .orderByDesc(FineRecord::getCreateTime);

        List<FineRecord> fineRecords = list(wrapper);
        List<FineRecordVO> vos = fineRecords.stream()
                                           .map(this::convertToVO)
                                           .collect(Collectors.toList());

        return Result.success(vos);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<FineRecordVO> createFineRecord(FineRecordCreateDTO createDTO) {
        log.info("创建罚金记录，参数：{}", createDTO);

        // 验证借阅记录是否存在
        if (createDTO.getBorrowRecordId() != null) {
            BorrowRecord borrowRecord = borrowRecordMapper.selectById(createDTO.getBorrowRecordId());
            if (borrowRecord == null) {
                return Result.fail(ResultCode.NOT_FOUND.getCode(), "借阅记录不存在", null);
            }
        }

        FineRecord fineRecord = new FineRecord();
        BeanUtils.copyProperties(createDTO, fineRecord);
        fineRecord.setId(UUID.randomUUID().toString());
        fineRecord.setPaymentStatus(0); // 默认未支付
        fineRecord.setCreateTime(LocalDateTime.now());
        fineRecord.setUpdateTime(LocalDateTime.now());

        save(fineRecord);

        FineRecordVO vo = convertToVO(fineRecord);
        log.info("罚金记录创建成功，ID：{}", fineRecord.getId());
        return Result.success(vo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<FineRecordVO> updateFineRecord(String id, FineRecordUpdateDTO updateDTO) {
        log.info("更新罚金记录，ID：{}，参数：{}", id, updateDTO);

        if (id == null || id.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID不能为空", null);
        }

        FineRecord fineRecord = getById(id);
        if (fineRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "罚金记录不存在", null);
        }

        // 只允许更新特定字段
        if (updateDTO.getFineAmount() != null) {
            fineRecord.setFineAmount(updateDTO.getFineAmount());
        }
        if (updateDTO.getDescription() != null) {
            fineRecord.setDescription(updateDTO.getDescription());
        }
        if (updateDTO.getPaymentStatus() != null) {
            fineRecord.setPaymentStatus(updateDTO.getPaymentStatus());
        }
        fineRecord.setUpdateTime(LocalDateTime.now());

        updateById(fineRecord);

        FineRecordVO vo = convertToVO(fineRecord);
        log.info("罚金记录更新成功，ID：{}", id);
        return Result.success(vo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<Void> deleteFineRecord(String id) {
        log.info("删除罚金记录，ID：{}", id);

        if (id == null || id.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID不能为空", null);
        }

        FineRecord fineRecord = getById(id);
        if (fineRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "罚金记录不存在", null);
        }

        // 检查是否已支付，已支付的不能删除
        if (fineRecord.getPaymentStatus() != null && fineRecord.getPaymentStatus() == 1) {
            return Result.fail(ResultCode.PRECONDITION_FAILED.getCode(), "已支付的罚金记录不能删除", null);
        }

        removeById(id);

        log.info("罚金记录删除成功，ID：{}", id);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<Void> batchDeleteFineRecords(List<String> ids) {
        log.info("批量删除罚金记录，数量：{}", ids.size());

        if (ids == null || ids.isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID列表不能为空", null);
        }

        // 检查是否有已支付的记录
        LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(FineRecord::getId, ids)
               .eq(FineRecord::getPaymentStatus, 1);
        
        long paidCount = count(wrapper);
        if (paidCount > 0) {
            return Result.fail(ResultCode.PRECONDITION_FAILED.getCode(), 
                    String.format("有%d条已支付的罚金记录不能删除", paidCount), null);
        }

        removeByIds(ids);

        log.info("批量删除罚金记录成功，数量：{}", ids.size());
        return Result.success();
    }

    /**
     * 转换为VO对象
     */
    private FineRecordVO convertToVO(FineRecord fineRecord) {
        FineRecordVO vo = new FineRecordVO();
        BeanUtils.copyProperties(fineRecord, vo);

        // 设置关联数据
        try {
            if (fineRecord.getBorrowRecordId() != null) {
                BorrowRecord borrowRecord = borrowRecordMapper.selectById(fineRecord.getBorrowRecordId());
                if (borrowRecord != null) {
                    vo.setBorrowRecordId(borrowRecord.getId());
                    vo.setUserId(borrowRecord.getUserId());
                    // BorrowRecord没有bookTitle字段，需要通过bookId查询
                    // 这里暂时设置为空，实际项目中需要关联查询Book表
                }
            }

            // 设置状态描述
            vo.setPaymentStatusName(fineRecord.getPaymentStatusName());

        } catch (Exception e) {
            log.warn("获取罚金记录关联数据失败，记录ID：{}", fineRecord.getId(), e);
        }

        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<Void> payFine(String id, String paymentMethod, String transactionId) {
        log.info("支付罚金，ID：{}，支付方式：{}，交易ID：{}", id, paymentMethod, transactionId);

        if (id == null || id.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID不能为空", null);
        }

        FineRecord fineRecord = getById(id);
        if (fineRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "罚金记录不存在", null);
        }

        if (fineRecord.isFullyPaid()) {
            return Result.fail(ResultCode.CONFLICT.getCode(), "罚金已支付", null);
        }

        // 使用实体的支付方法
        boolean success = fineRecord.recordPayment(fineRecord.getUnpaidAmount(), paymentMethod, transactionId);
        if (!success) {
            return Result.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "支付记录失败", null);
        }

        fineRecord.setUpdateTime(LocalDateTime.now());

        updateById(fineRecord);

        log.info("罚金支付成功，ID：{}", id);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<Void> waiveFine(String id, BigDecimal waiveAmount, String waiveReason) {
        log.info("减免罚金，ID：{}，减免金额：{}，减免原因：{}", id, waiveAmount, waiveReason);

        if (id == null || id.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID不能为空", null);
        }

        FineRecord fineRecord = getById(id);
        if (fineRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "罚金记录不存在", null);
        }

        if (fineRecord.isFullyPaid()) {
            return Result.fail(ResultCode.CONFLICT.getCode(), "已支付的罚金不能减免", null);
        }

        if (waiveAmount.compareTo(fineRecord.getFineAmount()) > 0) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "减免金额不能大于罚金金额", null);
        }

        // 减免处理：直接减少罚金金额
        fineRecord.setFineAmount(fineRecord.getFineAmount().subtract(waiveAmount));

        // 如果减免后金额为0，设为已支付
        if (fineRecord.getFineAmount().compareTo(BigDecimal.ZERO) == 0) {
            fineRecord.setPaymentStatus(1); // 已支付
            fineRecord.setPaymentTime(LocalDateTime.now());
        }

        // 在描述中记录减免信息
        String newDescription = String.format("减免金额：%s，减免原因：%s", waiveAmount, waiveReason);
        if (fineRecord.getDescription() != null) {
            fineRecord.setDescription(fineRecord.getDescription() + "；" + newDescription);
        } else {
            fineRecord.setDescription(newDescription);
        }

        fineRecord.setUpdateTime(LocalDateTime.now());

        updateById(fineRecord);

        log.info("罚金减免成功，ID：{}", id);
        return Result.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<Void> cancelFine(String id, String cancelReason) {
        log.info("取消罚金，ID：{}，取消原因：{}", id, cancelReason);

        if (id == null || id.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "罚金记录ID不能为空", null);
        }

        FineRecord fineRecord = getById(id);
        if (fineRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "罚金记录不存在", null);
        }

        if (fineRecord.isFullyPaid()) {
            return Result.fail(ResultCode.CONFLICT.getCode(), "已支付的罚金不能取消", null);
        }

        // 取消处理：将罚金金额设为0，并在描述中记录取消信息
        fineRecord.setFineAmount(BigDecimal.ZERO);

        String cancelDescription = String.format("罚金已取消，取消原因：%s", cancelReason);
        if (fineRecord.getDescription() != null) {
            fineRecord.setDescription(fineRecord.getDescription() + "；" + cancelDescription);
        } else {
            fineRecord.setDescription(cancelDescription);
        }

        fineRecord.setUpdateTime(LocalDateTime.now());

        updateById(fineRecord);

        log.info("罚金取消成功，ID：{}", id);
        return Result.success();
    }

    @Override
    public Result<BigDecimal> calculateOverdueFine(String borrowRecordId, Integer overdueDays) {
        log.info("计算逾期罚金，借阅记录ID：{}，逾期天数：{}", borrowRecordId, overdueDays);

        if (borrowRecordId == null || borrowRecordId.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "借阅记录ID不能为空", null);
        }

        if (overdueDays == null || overdueDays <= 0) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "逾期天数必须大于0", null);
        }

        // 计算罚金：逾期天数 * 每日罚金率
        BigDecimal fineAmount = dailyFineRate.multiply(BigDecimal.valueOf(overdueDays));

        // 限制最大罚金金额
        if (fineAmount.compareTo(maxFineAmount) > 0) {
            fineAmount = maxFineAmount;
        }

        log.info("逾期罚金计算完成，金额：{}", fineAmount);
        return Result.success(fineAmount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "fineRecords", allEntries = true)
    public Result<FineRecordVO> generateOverdueFine(String borrowRecordId) {
        log.info("自动生成逾期罚金记录，借阅记录ID：{}", borrowRecordId);

        if (borrowRecordId == null || borrowRecordId.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "借阅记录ID不能为空", null);
        }

        // 验证借阅记录是否存在
        BorrowRecord borrowRecord = borrowRecordMapper.selectById(borrowRecordId);
        if (borrowRecord == null) {
            return Result.fail(ResultCode.NOT_FOUND.getCode(), "借阅记录不存在", null);
        }

        // 检查是否已有罚金记录
        LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FineRecord::getBorrowRecordId, borrowRecordId)
               .eq(FineRecord::getFineType, 1); // 1-逾期罚金

        if (count(wrapper) > 0) {
            return Result.fail(ResultCode.CONFLICT.getCode(), "该借阅记录已有逾期罚金记录", null);
        }

        // 计算逾期天数
        if (borrowRecord.getDueDate() == null) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "借阅记录缺少应还日期", null);
        }

        LocalDateTime now = LocalDateTime.now();
        long overdueDays = ChronoUnit.DAYS.between(borrowRecord.getDueDate(), now);

        if (overdueDays <= 0) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "图书未逾期", null);
        }

        // 计算罚金金额
        Result<BigDecimal> fineAmountResult = calculateOverdueFine(borrowRecordId, (int) overdueDays);
        if (!fineAmountResult.isSuccess()) {
            return Result.fail(fineAmountResult.getCode(), fineAmountResult.getMsg(), null);
        }

        // 创建罚金记录
        FineRecord fineRecord = new FineRecord();
        fineRecord.setId(UUID.randomUUID().toString());
        fineRecord.setUserId(borrowRecord.getUserId());
        fineRecord.setBorrowRecordId(borrowRecordId);
        fineRecord.setFineType(1); // 1-逾期罚金
        fineRecord.setFineAmount(fineAmountResult.getData());
        fineRecord.setDescription(String.format("图书逾期%d天", overdueDays));
        fineRecord.setPaymentStatus(0); // 未支付
        fineRecord.setCreateTime(LocalDateTime.now());
        fineRecord.setUpdateTime(LocalDateTime.now());

        save(fineRecord);

        FineRecordVO vo = convertToVO(fineRecord);
        log.info("逾期罚金记录生成成功，ID：{}，金额：{}", fineRecord.getId(), fineRecord.getFineAmount());
        return Result.success(vo);
    }

    @Override
    public Result<BigDecimal> getUnpaidFineAmount(String userId) {
        log.info("获取用户未支付罚金总额，用户ID：{}", userId);

        if (userId == null || userId.trim().isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "用户ID不能为空", null);
        }

        try {
            LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FineRecord::getUserId, userId)
                   .eq(FineRecord::getPaymentStatus, 0); // 未支付

            List<FineRecord> unpaidFines = list(wrapper);
            BigDecimal totalAmount = unpaidFines.stream()
                    .map(FineRecord::getFineAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            return Result.success(totalAmount);
        } catch (Exception e) {
            log.error("获取用户未支付罚金总额失败，用户ID：{}", userId, e);
            return Result.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "获取罚金总额失败", null);
        }
    }

    @Override
    public Result<FineStatisticsVO> getFineStatistics(String userId) {
        log.info("获取罚金统计信息，用户ID：{}", userId);

        try {
            FineStatisticsVO statistics = new FineStatisticsVO();

            LambdaQueryWrapper<FineRecord> wrapper = new LambdaQueryWrapper<>();
            if (userId != null && !userId.trim().isEmpty()) {
                wrapper.eq(FineRecord::getUserId, userId);
            }

            List<FineRecord> fineRecords = list(wrapper);
            statistics.setTotalRecords(fineRecords.size());

            if (!fineRecords.isEmpty()) {
                // 计算总金额
                BigDecimal totalAmount = fineRecords.stream()
                        .map(FineRecord::getFineAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                statistics.setTotalAmount(totalAmount);

                // 按状态统计
                List<FineRecord> paidRecords = fineRecords.stream().filter(f -> f.getPaymentStatus() == 1).collect(Collectors.toList());
                List<FineRecord> unpaidRecords = fineRecords.stream().filter(f -> f.getPaymentStatus() == 0).collect(Collectors.toList());
                List<FineRecord> partiallyPaidRecords = fineRecords.stream().filter(f -> f.getPaymentStatus() == 2).collect(Collectors.toList());
                List<FineRecord> cancelledRecords = fineRecords.stream().filter(f -> f.getFineAmount().compareTo(BigDecimal.ZERO) == 0 && f.getDescription() != null && f.getDescription().contains("已取消")).collect(Collectors.toList());

                statistics.setPaidRecords(paidRecords.size());
                statistics.setUnpaidRecords(unpaidRecords.size());
                statistics.setWaivedRecords(partiallyPaidRecords.size()); // 用部分支付记录数代替减免记录数
                statistics.setCancelledRecords(cancelledRecords.size());

                // 计算各状态金额
                statistics.setPaidAmount(paidRecords.stream().map(FineRecord::getFineAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                statistics.setUnpaidAmount(unpaidRecords.stream().map(FineRecord::getFineAmount).reduce(BigDecimal.ZERO, BigDecimal::add));
                statistics.setWaivedAmount(partiallyPaidRecords.stream().map(f -> f.getPaidAmount() != null ? f.getPaidAmount() : BigDecimal.ZERO).reduce(BigDecimal.ZERO, BigDecimal::add));
            } else {
                statistics.setTotalAmount(BigDecimal.ZERO);
                statistics.setPaidAmount(BigDecimal.ZERO);
                statistics.setUnpaidAmount(BigDecimal.ZERO);
                statistics.setWaivedAmount(BigDecimal.ZERO);
                statistics.setPaidRecords(0);
                statistics.setUnpaidRecords(0);
                statistics.setWaivedRecords(0);
                statistics.setCancelledRecords(0);
            }

            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取罚金统计信息失败，用户ID：{}", userId, e);
            return Result.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "获取统计信息失败", null);
        }
    }

    @Override
    public Result<String> importFineRecords(List<FineRecordCreateDTO> fineRecords) {
        log.info("导入罚金记录数据，数量：{}", fineRecords.size());

        if (fineRecords == null || fineRecords.isEmpty()) {
            return Result.fail(ResultCode.PARAM_ERROR.getCode(), "导入数据不能为空", null);
        }

        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMessages = new StringBuilder();

        for (int i = 0; i < fineRecords.size(); i++) {
            FineRecordCreateDTO dto = fineRecords.get(i);
            try {
                Result<FineRecordVO> result = createFineRecord(dto);
                if (result.isSuccess()) {
                    successCount++;
                } else {
                    failCount++;
                    errorMessages.append("第").append(i + 1).append("行：").append(result.getMsg()).append("；");
                }
            } catch (Exception e) {
                failCount++;
                errorMessages.append("第").append(i + 1).append("行：").append(e.getMessage()).append("；");
                log.error("导入第{}行数据失败", i + 1, e);
            }
        }

        String resultMessage = String.format("导入完成，成功：%d条，失败：%d条", successCount, failCount);
        if (failCount > 0) {
            resultMessage += "。失败原因：" + errorMessages.toString();
        }

        log.info("罚金记录数据导入完成，成功：{}条，失败：{}条", successCount, failCount);
        return Result.success(resultMessage);
    }

    @Override
    public Result<String> exportFineRecords(FineRecordQuery query) {
        log.info("导出罚金记录数据，查询条件：{}", query);

        try {
            if (query == null) {
                query = new FineRecordQuery();
            }

            query.setSize(10000); // 最多导出10000条记录
            PageResult<FineRecordVO> pageResult = getFineRecordPage(query);

            if (pageResult == null || pageResult.getRecords() == null || pageResult.getRecords().isEmpty()) {
                return Result.fail(ResultCode.NOT_FOUND.getCode(), "没有找到符合条件的数据", null);
            }

            String timestamp = String.valueOf(System.currentTimeMillis());
            String fileName = "fine_records_export_" + timestamp + ".xlsx";
            String filePath = "/exports/" + fileName;

            log.info("模拟生成Excel文件，包含{}条记录，文件路径：{}", pageResult.getRecords().size(), filePath);

            String resultMessage = String.format("导出成功，共%d条记录，文件：%s",
                pageResult.getRecords().size(), fileName);

            log.info("罚金记录数据导出完成，记录数：{}，文件：{}", pageResult.getRecords().size(), fileName);
            return Result.success(resultMessage);

        } catch (Exception e) {
            log.error("导出罚金记录数据失败", e);
            return Result.fail(ResultCode.INTERNAL_SERVER_ERROR.getCode(), "导出失败：" + e.getMessage(), null);
        }
    }
}
